package qualomelhor.server;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.*; 
import org.apache.commons.io.IOUtils;
import qualomelhor.database.LinkBlobImage;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.images.Composite;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class TestUrlFetchServlet extends HttpServlet { 

	private static final long serialVersionUID = 0;

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { 

	    ImagesService imagesService = ImagesServiceFactory.getImagesService();

		String strUrl = req.getParameter("url");

		System.out.println("url = " + strUrl);

		try {

			URL url = new URL(strUrl);

			InputStream in = url.openStream();
			Blob content = new Blob(IOUtils.toByteArray(in));

			LinkBlobImage linkBlogImg = new LinkBlobImage("/img/myImageTest", content);

			Image aImage = ImagesServiceFactory.makeImage(linkBlogImg.getImage().getBytes());

			Transform resize = ImagesServiceFactory.makeResize(50, 50);
	        Image nAImage = imagesService.applyTransform(resize, aImage);

			Image bImage = ImagesServiceFactory.makeImage(linkBlogImg.getImage().getBytes());
	        Image nBImage = imagesService.applyTransform(resize, bImage);

		  	List<Composite> listComposites=new ArrayList<Composite>();

		    Composite aPaste = ImagesServiceFactory.makeComposite(nAImage, 0, 0, 1f, Composite.Anchor.TOP_LEFT);
		    listComposites.add( aPaste );

		    Composite bPaste = ImagesServiceFactory.makeComposite(nBImage, 50, 0, 1f, Composite.Anchor.TOP_LEFT);
		    listComposites.add( bPaste );

		    Image newImage = imagesService.composite(listComposites, 100, 50, 0x00000000L, ImagesService.OutputEncoding.PNG);

		    LinkBlobImage newLBlob = new LinkBlobImage("", new Blob(newImage.getImageData()));

			DAO d = new DAO();
			long result = d.gravaNovoLinkBlobImage(newLBlob, true);
			if (result > 0) {
				System.out.println("result ok - redirecting");
				resp.sendRedirect("/img/" + result);
			} else {
				System.out.println("result fail");
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("fim");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		doPost(req, resp);
	}
}